<?php /* УТФ-8:fix */

class SPIcontroller__front extends SPIcontroller__dummy
{
    public $MENU_TOPS = null;
    public $MENU_SUBS = null;

    public function exec()
    {
        $content = array();
        $show_homepage = false;

        // --------------------------------------------------------------------

        list( $content['env_lang'], $content['env_topic'], $content['env_action'], $content['env_vars'] ) = SPIc::I('front')->link->parse_env();
		
		SPI::I('lang')->set_default('ru');
		
        // --------------------------------------------------------------------

        $content['linkway'] = array();

        $content['linkway'][] = array(
            'name' => 'Главная',
            'link' => SPIc::I('front')->link->homepage(),
        );

        $this->overall( $content );

        // --------------------------------------------------------------------

        switch( $content['env_topic'] )
        {
            case 'news':
            case 'catalog':
            case 'gallery':
            case 'partners':
            case 'product':
            {
                $show_homepage = false === SPIc::I('content')->front->exec( $content );
                break;
            }

            case 'contacts':
            case 'about':
            {
                $show_homepage = false === SPIc::I('singlepage')->front->exec( $content );
                break;
            }

            default:
            {
                $show_homepage = true;
                break;
            }
        }

        if( $show_homepage === true )
        {
            $content['env_topic'] = 'home';
            $this->exec_home( $content );
        }
		
		$content['meta'] = $this->generate_meta_content( $content['linkway'] );
		
        SPIv::I('front')->render( $content );

        return true;
    }

    public function menu( & $content )
    {
        $content['menu'] = array();

        $content['menu']['homepage'] = array(
            'name'      => 'Главная',
            'link'      => SPIc::I('front')->link->homepage(),
            'items'     => array(),
            'is_active' => $content['env_topic'] == 'home' ? true : false,
        );

        // --------------------------------------------------------------------

        $content['menu']['partners'] = array(
            'name'      => SPI::I('lang')->content->typename['partners'],
            'items'     => array(),
            'link'      => SPIc::I('front')->link->content('partners'),
            'is_active' => in_array( $content['env_topic'], array( 'partners' ) ),
        );
		
        // --------------------------------------------------------------------

        $content['menu']['product'] = array(
            'name'      => SPI::I('lang')->content->typename['product'],
            'items'     => array(),
            'link'      => SPIc::I('front')->link->content('product'),
            'is_active' => in_array( $content['env_topic'], array( 'product' ) ),
        );		
		
        // --------------------------------------------------------------------

        $content['menu']['gallery'] = array(
            'name'      => SPI::I('lang')->content->typename['gallery'],
            'link'      => SPIc::I('front')->link->content('gallery'),
            'is_active' => in_array( $content['env_topic'], array( 'gallery' ) ),
        );
		
        // --------------------------------------------------------------------

        $content['menu']['news'] = array(
            'name'      => SPI::I('lang')->content->typename['news'],
            'link'      => SPIc::I('front')->link->content('news'),
            'is_active' => in_array( $content['env_topic'], array( 'news' ) ),
        );

        // --------------------------------------------------------------------

        $content['menu']['contacts'] = array(
            'name'      => SPI::I('lang')->singlepage->typename['contacts'],
            'link'      => SPIc::I('front')->link->content('contacts'),
            'is_active' => in_array( $content['env_topic'], array( 'contacts' ) ),
        );
		
        // --------------------------------------------------------------------

        $content['menu']['about'] = array(
            'name'      => SPI::I('lang')->singlepage->typename['about'],
            'link'      => SPIc::I('front')->link->content('about'),
            'is_active' => in_array( $content['env_topic'], array( 'about' ) ),
        );

        // --------------------------------------------------------------------

        return true;
    }

    public function exec_home( & $content )
    {
        $content['topic_template_filename'] = 'home/main.tpl';
        $content['active_topic'] = 'home';

        //$content['home']['news']     = SPIc::I('content')->front->get_last_content( 'news' );
        //$content['home']['catalogs'] = SPIc::I('content')->front->get_last_content( 'catalog', 't_created-', 4 );
        //$content['home']['partners'] = SPIc::I('content')->front->get_last_content( 'partners', 'order_index', 4 );

        return true;
    }

    public function overall( & $content )
    {
        //$content['logo']                = SPIc::I('logos')->front->get_random();
		
        $this->menu( $content );

        $content['link_homepage']       = SPIc::I('front')->link->homepage();
        $content['link_self']           = SPIc::I('front')->link->selflink();

        $content['link_minify_css']     = SPIc::I('front')->link->minify('css');
        $content['link_minify_js']      = SPIc::I('front')->link->minify('js');

        $content['url_homepage']        = SPIc::I('front')->link->absolute( $content['link_homepage'] );
        $content['url_self']            = SPIc::I('front')->link->absolute( $content['link_self'] );

        //$content['const']               = SPIc::I('consts')->front->get_list();
		
		SPIc::I('catalogs')->front->buildCatalogsTree( $content['catalogs'], $content['env_vars']['cat'] );
		//vd($content['catalogs']);
		/*
		$content['contact_info'] = array();
		foreach( $content['const'] as $key => $const )
		{
			$dat = explode( '_', $key );
			
			if( $dat[0] == 'contact' )
			{
				$content['contact_info'][$dat[1]] = array(
					'name' => SPI::I('lang')->consts->typename[ $dat[1] ],
					'info' => str_replace(',', "\n", $const)
				);
			}
		}
*/
        return true;
    }

    public function exec_error404page()
    {
        header("HTTP/1.0 404 Not Found");

        SPI::I('lang')->set_default('ru');

        $content = array();
        $content['link_homepage']   = SPIc::I('front')->link->homepage();
        $content['link_sitemap']    = SPIc::I('front')->link->standard('sitemap');
        $content['link_minify_css'] = SPIc::I('front')->link->minify('css');
        $content['link_minify_js']  = SPIc::I('front')->link->minify('js');

        $this->menu( $content );

        SPIv::I('front')->render( $content, 'error404page.tpl' );

        return true;
    }
	
    private function generate_meta_content( $linkway )
    {
        if( is_array( $linkway ) === false )
        {
            $linkway = array();
        }
        elseif( count( $linkway ) > 0 )
        {
            array_shift( $linkway ); // drop 1st-HOME-item

            $linkway = array_reverse( $linkway );
        }

        //---------------------------------------------------------------------
        // Meta title generate

        $title = array();
		
        if( $linkway[0]['fixed_meta_title'] )
        {
            $title[] = $linkway[0]['fixed_meta_title'];
        }
        else
        {
            foreach( $linkway as $item )
            {
                if( $item['name'] )
                {
                    $title[] = $item['name'];
                }
            }
        }
		
        $title[] = SPIcfg::$project_name;
		$title   = join( ', ', $title );

        //---------------------------------------------------------------------
        // Meta description generate

        if( $linkway[0]['fixed_meta_descr'] )
        {
            $descr = $linkway[0]['fixed_meta_descr'];
        }
        else
        {
            $descr = array();

            if( isset( $linkway[0] ) === true )
            {
                $descr[] = $linkway[0]['name'];

                if( $linkway[0]['anons'] )
                {
                    $descr[] = $linkway[0]['anons'];
                }
                elseif( $linkway[0]['description'] )
                {
                    $anons = $linkway[0]['description'];
                    $anons = SPItpl__smarty__extensions::spiStripTags( $anons );
                    $anons = trim( preg_replace( '#[\r\n]+#', ' ', $anons ) );
                    $anons = SPItpl__smarty__extensions::spiTruncate( $anons, 250 );

                    if( $anons != '' )
                    {
                        $descr[] = $anons;
                    }
                }
            }

            $descr[] = ''; // default meta-description
            $descr   = join( '. ', $descr );
        }

        //---------------------------------------------------------------------
        // Meta keywords generate

        $keywords = '';

        if( $linkway[0]['fixed_meta_keywords'] )
        {
            $keywords = $linkway[0]['fixed_meta_keywords'];
        }
        elseif( isset( $linkway[0] ) === true )
        {
            if( count( $linkway[0]['keywords_list'] ) > 0 ) // Generate keywords from list of content
            {
                $keywords = $this->unpack_keywords_from_text( $linkway[0]['name'] );

                foreach( $linkway[0]['keywords_list'] as $keyword_item )
                {
                    $keywords = array_merge( $keywords, $this->unpack_keywords_from_text( $keyword_item ) );
                }
            }
            else
            {
                $keywords = $this->unpack_keywords_from_text(
                                $linkway[0]['name'],
                                $linkway[0]['anons'].$linkway[0]['description'],
                                $linkway[0]['tags']
                            );
            }

            $keywords = join( ',', array_unique( $keywords ) );
        }

        if( $keywords == '' )
        {
            $keywords = ''; // meta-keywords
        }

        //---------------------------------------------------------------------

        return array(
            'title'    => $title,
            'descr'    => $descr,
            'keywords' => $keywords,
        );
    }

    private function unpack_keywords_from_text( $title, $text = null, $tags_array = null )
    {
        $regexp  = '#[^а-яa-zіїєґё]#iu';

        //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        $title   = preg_replace( $regexp, ' ', $title );
        $k_title = explode( ' ', trim( preg_replace( '# +#', ' ', $title ) ) );

        if( count( $k_title ) > 5 )
        {
            $k_title = array_splice( $k_title, 0, 5 );
        }

        //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        $k_text  = array();

        if( $text )
        {
            $text    = strip_tags( $text );
            $text    = preg_replace( $regexp, ' ', $text );
            $text    = explode( ' ', trim( preg_replace( '# +#', ' ', $text ) ) );

            $this->keywords_array = array();

            foreach( $text as $word )
            {
                if( strlen($word)/2 /* UTF-8 fix */ <= 3 )
                {
                    continue;
                }

				$this->keywords_array[ mb_strtolower($word,'UTF-8') ]++;
            }

            uksort( $this->keywords_array, array( self, 'keywords_array_sort' ) );

            $used_count = 0;
            foreach( $this->keywords_array as $word => $count )
            {
                if( $count == 1 )           break;
                if( $used_count++ == 15 )   break;

                $k_text[] = $word;
            }
            unset( $this->keywords_array );
        }

        //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        $k_tags = array();

        if( $tags_array )
        {
            if( is_array( $tags_array ) )
            foreach( $tags_array as $tag_item )
            {
                $k_tags[] = $tag_item['tag'];
            }
        }

        //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        $keywords = array();
        $keywords = array_merge( $keywords, $k_title );
        $keywords = array_merge( $keywords, $k_text );
        $keywords = array_merge( $keywords, $k_tags );

        return array_unique( $keywords );
    }

    private $keywords_array = null;

    private function keywords_array_sort( $key1, $key2 )
    {
        if( $this->keywords_array[$key1] == $this->keywords_array[$key2] )
        {
            return 0;
        }

        return $this->keywords_array[$key1] < $this->keywords_array[$key2] ? 1 : -1;
    }
	
	public function build_pages_indexes( $page_index, $pages_count )
	{
		$r = array();

		for( $i=1, $flags=array(); $i<=$pages_count; $flags[$i]=false, $i++ );

		for( $i=0; $i<3; $i++ )
		{
			$flags[1+$i]=true;
		}

		for( $i=0; $i<5; $i++ )
		{
			$flags[1+$i]=true;
			$flags[$page_index-$i]=true;
			$flags[$page_index+$i]=true;
			$flags[$pages_count-$i]=true;
		}

		for( $i=1, $last_dots=false; $i<=$pages_count; $i++ )
		{
			if( $flags[$i] === false )
			{
				if( $last_dots === false )
				{
					$r[$i] = '..';
					$last_dots = true;
				}
				continue;
			}

			$r[$i] = $i;
			$last_dots = false;
		}

		return $r;
	}
}
